
package at.fhj.ase.crypto.client.security;

import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import org.slf4j.Logger;

import at.fhj.ase.crypto.common.util.CryptoUtil;
import at.fhj.ase.crypto.common.util.LogUtil;

/**
 * Class responsible for all key operations like creating a public/private key pair and also sharing the key with other classes.<br>
 * As only one key pair should exist, this class is implemented as a singleton pattern
 * 
 * @author sfe | www.fh-joanneum.at | Practical Aspects of Cryptography
 * @throws IllegalStateException if there is a problem at key creation
 */
public class SecurityController {
  /** The logging instance */
  private static final Logger logger = LogUtil.getLogger();
  /** The sole instance of this class */
  private static SecurityController INSTANCE;

  /** The public key of this client (part of keypair) */
  private final PublicKey publicKey;
  /** The private key of this client (part of keypair) */
  private final PrivateKey privateKey;

  /**
   * Generates the sole instance of this class by calling the constructor.
   * 
   * @return the sole instance of this class
   * @throws IllegalStateException if an exception occured while instantiating
   */
  public static SecurityController getInstance() {
    if (INSTANCE == null) {
      try {
        INSTANCE = new SecurityController();
      } catch (NoSuchAlgorithmException e) {
        logger.error("Could not create instance of SecurityController", e);
        throw new IllegalStateException(e);
      }
    }
    return INSTANCE;
  }

  /**
   * Constructor initiating the public and private key pair
   * 
   * @throws NoSuchAlgorithmException if there occurs an error at initiating the key pair
   */
  private SecurityController() throws NoSuchAlgorithmException {
    // generate a key pair and establish the connection to server
    final KeyPair keyPair = CryptoUtil.createKeyPair(CryptoUtil.RSA, 1024);
    publicKey = keyPair.getPublic();
    privateKey = keyPair.getPrivate();
  }

  /** @returnt the public key of this client (part of key pair) */
  public PublicKey getPublicKey() {
    return publicKey;
  }

  /** @return the private key of this client (part of key pair) */
  public PrivateKey getPrivateKey() {
    return privateKey;
  }
}
